package shuaige.jdk.集合.映射表集合Map;

import shuaige.jdk.model.PersonNoEqualsAndHashCode;

import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/**
 * 排序要实现Comparable接口compare方法，要实现3个逻辑 0 相等 1 大于 -1 小于
 * TreeMap不需要覆写equals()和hashCode()
 */
public class 排序Map使用TreeMap {
    public static void main(String[] args) {
        Map<PersonNoEqualsAndHashCode, Integer> map = new TreeMap<>(new Comparator<PersonNoEqualsAndHashCode>() {
            @Override
            public int compare(PersonNoEqualsAndHashCode p1, PersonNoEqualsAndHashCode p2) {
                if (Objects.equals(p1.getAge(), p2.getAge())) {
                    return 0;
                }
                return p1.getAge() > p2.getAge() ? -1 : 1;
            }
        });
        map.put(new PersonNoEqualsAndHashCode("Tom", 77), 1);
        map.put(new PersonNoEqualsAndHashCode("Bob", 66), 2);
        map.put(new PersonNoEqualsAndHashCode("Lily", 99), 3);
        for (PersonNoEqualsAndHashCode key : map.keySet()) {
            System.out.println(key);
        }
        System.out.println(map.get(new PersonNoEqualsAndHashCode("Bob", 66))); // null?
    }

    public static void string类有实现Comparable接口() {
        Map<String, Integer> map = new TreeMap<>();
        map.put("orange", 1);
        map.put("apple", 2);
        map.put("pear", 3);
        for (String key : map.keySet()) {
            System.out.println(key);
        }
    }

    public static void 自定义实现Comparator接口() {
        Map<PersonNoEqualsAndHashCode, Integer> map = new TreeMap<>(new Comparator<PersonNoEqualsAndHashCode>() {
            @Override
            public int compare(PersonNoEqualsAndHashCode p1, PersonNoEqualsAndHashCode p2) {
                // 按照年龄倒序排序
                return p2.getAge().compareTo(p1.getAge());
            }
        });

        map.put(new PersonNoEqualsAndHashCode("Tom", 1), 1);
        map.put(new PersonNoEqualsAndHashCode("Bob", 2), 2);
        map.put(new PersonNoEqualsAndHashCode("Lily", 3), 3);
        for (Map.Entry<PersonNoEqualsAndHashCode, Integer> entry : map.entrySet()) {
            System.out.println(entry);
        }
        System.out.println(map.get(new PersonNoEqualsAndHashCode("Bob", 2)));
    }

}
